﻿package
{
	import events.LoaderEvent;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import gs.OverwriteManager;
	import interfaces.IMain;
	import model.ApplicationModel;
	import model.ApplicationView;
	
	/**
	 * ...
	 * @author kasoi (fsca.ru)
	 */
	public class Main extends Sprite implements IMain
	{
		
		private var content: Sprite;
		
		private var callMethod: Function;
		
		////////////////////////////////////////////////////////////////////
		// Public methods
		////////////////////////////////////////////////////////////////////
		
		public function Main() : void 
		{
			if (this.stage) this.init();
			else this.addEventListener(Event.ADDED_TO_STAGE, this.this_onAddedToStage);
		}
		
		public function onChange(method: Function) : void 
		{
			this.callMethod = method;
		}
		
		////////////////////////////////////////////////////////////////////
		// Private methods
		////////////////////////////////////////////////////////////////////
		
		private function init() : void 
		{
			StageManager.init(this.stage);
			Log.init();
			Texts.instance = new Texts();
			OverwriteManager.init(OverwriteManager.AUTO);
			
			this.loadTexts();
		}
		
		private function loadTexts() : void 
		{
			Texts.instance.loadTexts();
			Texts.instance.addEventListener(LoaderEvent.LOAD_COMPLETE, 
				this.texts_onComplete);
		}
		
		private function initApplication() : void 
		{
			this.content = new Sprite();
			this.addChild(this.content);
			
			ApplicationView.getInstance().init(this.content);
			ApplicationModel.getInstance().init();
		}
		
		////////////////////////////////////////////////////////////////////
		// Listeners
		////////////////////////////////////////////////////////////////////
		
		private function this_onAddedToStage(e: Event = null) : void 
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, this.this_onAddedToStage);
			this.init();
		}
		
		private function texts_onComplete(e: LoaderEvent) : void 
		{
			if (this.callMethod != null) this.callMethod();
			this.initApplication();
		}
	}
	
}